package handlers

import (
	"backend/internal/database"
	"backend/models"
	"backend/pkg/log"
	"backend/pkg/utils"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type RegisterRequest struct {
	Name       string `json:"name" binding:"required"`
	Email      string `json:"email" binding:"required,email"`
	Password   string `json:"password" binding:"required,min=6"`
	VerifyCode string `json:"verifyCode" binding:"required"`
}

type RegisterResponse struct {
	Token string      `json:"token"`
	User  models.User `json:"user"`
}

func Register(c *gin.Context) {
	startTime := time.Now()
	var req RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Error("请求参数绑定失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		log.RequestLog(c, startTime, "请求参数绑定失败")
		return
	}

	// 验证邮箱验证码
	if !VerifyEmailCode(req.Email, req.VerifyCode) {
		log.Warning("验证码错误: %s", req.Email)
		c.JSON(http.StatusBadRequest, gin.H{"error": "验证码错误"})
		log.RequestLog(c, startTime, "验证码错误")
		return
	}

	// 检查邮箱是否已存在
	var existingUser models.User
	if result := database.DB.Where("email = ?", req.Email).First(&existingUser); result.Error == nil {
		log.Warning("邮箱已被注册: %s", req.Email)
		c.JSON(http.StatusBadRequest, gin.H{"error": "邮箱已被注册"})
		log.RequestLog(c, startTime, "邮箱已被注册")
		return
	}

	// Rest of the registration logic remains the same...
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		log.Error("密码加密失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密失败"})
		log.RequestLog(c, startTime, "密码加密失败")
		return
	}

	user := models.User{
		Name:     req.Name,
		Email:    req.Email,
		Password: string(hashedPassword),
	}

	if result := database.DB.Create(&user); result.Error != nil {
		log.Error("用户创建失败: %v", result.Error)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "用户创建失败"})
		log.RequestLog(c, startTime, "用户创建失败")
		return
	}

	token, err := utils.GenerateToken(user.ID)
	if err != nil {
		log.Error("Token生成失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Token生成失败"})
		log.RequestLog(c, startTime, "Token生成失败")
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"token": token,
		"user": gin.H{
			"id":    user.ID,
			"name":  user.Name,
			"email": user.Email,
		},
	})

	log.Info("用户注册成功: id=%d, email=%s", user.ID, user.Email)
	log.RequestLog(c, startTime, "注册成功")
}
